package com.funo.oeip.regcenter.zkcli;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.data.Stat;

/**
 * 异步创建节点
 * @author simonfj
 *
 */
public class ZkClientAsyncWatcher implements Watcher {
	public static final String NODE_NAME = "/auth/node01"; 
	public static final String ZK_HOST = "localhost:2181";
	
    private static ZooKeeper zooKeeper;

	public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper(ZK_HOST,5000, new ZkClientAsyncWatcher());
            //System.out.println("State:" + zooKeeper.getState());
            Thread.sleep(10000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

	}

	public void process(WatchedEvent event) {
		KeeperState state = event.getState();
		
		//判断状态
		if (state.equals(Event.KeeperState.SyncConnected)) { 
			doBus();
		} else {
			System.out.println("Keeper state is:" + state.toString());
		}

	}
	
	private void doBus() {
        System.out.println("doBus!");
        try {
            if(null != zooKeeper.exists(NODE_NAME,false)) {
            	Stat stat = null;
            	byte[] data = zooKeeper.getData(NODE_NAME, this, stat);
                System.out.println(NODE_NAME+ "节点已存在,值:" + new String(data, "UTF-8"));
                
                
                return;
            }
            zooKeeper.create(NODE_NAME,"value001".getBytes("UTF-8"),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,new MyStringCallBack(),"testAsync");

        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}        
    }
	
    static class MyStringCallBack implements AsyncCallback.StringCallback {

        public void processResult(int rc, String path, Object ctx, String name) {
            System.out.println("resultcode="+rc);//创建成功返回0
            System.out.println("path="+path);//自定义节点名称
            System.out.println("ctx="+ctx);//自定义回调数据
            System.out.println("name="+name);//最终节点名称（顺序节点最终名称与自定义名称不同）

        }
    }	

}
